package org.example.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.example.util.SerializeUtil;

/**
 * @author mojito
 * @Classname RpcEncoder
 * @Description TODO
 * @Date 2020/7/22 下午9:30
 **/
public class RpcEncoder extends MessageToByteEncoder {

    private Class<?> generic;

    public RpcEncoder(Class<?> generic) {
        this.generic = generic;
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
        if (generic.isInstance(msg)) {
            byte[] data = SerializeUtil.serialize(msg);
            out.writeInt(data.length);
            out.writeBytes(data);
            System.out.println("encode success: length=" + data.length);
        }
    }
}
